package com.ibeetl.eval.worker;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Element;

import com.ibeetl.eval.EvalContext;
import com.ibeetl.eval.NodeWorker;
import com.ibeetl.eval.TreeNode;

public class SumNodeWorker implements NodeWorker {

	public  TreeNode execute(Element ele,EvalContext ctx){
		String name = ele.getAttributeValue("name");
		TreeNode currentNode =  ctx.enter(name, ele);
		List<Element> list = ele.getChildren();
		List<TreeNode> childrens = new ArrayList<TreeNode>();
		for(Element ruleEle:list){
			NodeWorker node = ctx.getEvalEngine().getRuleNode(ruleEle);
			TreeNode treeNode = node.execute(ruleEle, ctx);
			childrens.add(treeNode);
		}
		Object ret = SumNodeArth.getValue(childrens);
		ctx.exist();
		currentNode.setResult(ret);
		return currentNode;
	}
	
	static   class SumNodeArth  {

		public static Object getValue(List<TreeNode> list) {
			BigDecimal total = new BigDecimal(0); ;
			for(TreeNode node :list){
				String name = node.getNodeName();
				String type = ((Element)node.getNodeRefInfo()).getAttributeValue("f");
				
				Object ret = node.getResult();
				if(ret!=null&&ret instanceof Number){
					Number n = (Number)ret;
					BigDecimal b = null;
					if(n instanceof BigDecimal){
						b = (BigDecimal)n;
					}
					b = new BigDecimal(n.toString());
					total =total.add(b);
				}
				
				
			}
			return total;
		}

	}

}
